import { Gltf, useGLTF, useKeyboardControls } from "@react-three/drei";
import { GroupProps, useFrame } from "@react-three/fiber";
import { Select } from "@react-three/postprocessing";
import { useState, useRef, useEffect } from "react";
import * as THREE from 'three'
import { position as playerPosition } from "./Player";
import { useRouter } from "next/navigation";

const source = "/assets/factory_outside.glb"

export function Island(props: GroupProps&{position:number[]}) {
    const [choosed, choose] = useState(false);
    const [inRadius, setInRadius] = useState(false)
    const radius = 10;
    const position = new THREE.Vector3(...props.position)
    const [, get] = useKeyboardControls()
    const router = useRouter()

    const goToTheme= ()=>{
        router.push('/theme')
    }

    useFrame(() => {
        const { enter } = get()
        
        if(inRadius&& enter){
            goToTheme()
        }

        if (Math.abs(playerPosition.x - position.x) < radius && Math.abs(playerPosition.z - position.z) < radius) {
            setInRadius(true)
        }
        else
            setInRadius(false)

    })


    return (
        <>

            <Select enabled={choosed || inRadius} >
                <mesh>
                    <Gltf
                        onPointerOver={() => {
                            console.log(choosed)
                            choose(true)
                        }}
                        onPointerOut={() => {
                            console.log(choosed)
                            choose(false)
                        }}
                        onClick={()=>goToTheme()}
                        scale={choosed || inRadius ? 1.1 : 1}
                        src={source}
                        {...props}
                    />
                </mesh>
            </Select>

        </>
    )
}